/**
 * axios 二次分装文件
 * @constructor
 * @param { String } title - axios 二次分装
 * @param { String } author - Sky_sjr
 */

import axios from "axios";
import common from "./common";
import define from "./define";
import { Message } from 'element-ui'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: define.timeout
})

// 请求拦截
service.interceptors.request.use(config => {
    if (common.getStorage('token')) {
        config.headers.token = common.getStorage('token') || ''
    }
    return config
})

// 响应拦截
service.interceptors.response.use(
    res => {
        if (res.status >= 200 && res.status < 300) {
            return res.data
        }
        Message({
            message: res?.msg || res?.message || "请求出错，请重试",
            type: "error",
            duration: 1500
        })
        const e = new Error(res.msg)
        e.response = res
        return Promise.reject(e)
    },
    error => {
        Message({
            message: "请求出错，请重试",
            type: "error",
            duration: 1500
        });
        return Promise.reject(error);
    }
)

export default service